#coding:utf-8
from django.shortcuts import render
from .models import  Formshujus
from django.core.paginator import *
from django.http import HttpResponseRedirect,HttpResponse
from formapp.form import LoginForm

# Create your views here.
# def shaa(request):
#     if request.method==["POST"]:
#
#         if user :
#             response = HttpResponseRedirect('/form/index/')
#             return response
#         else:
#             return HttpResponseRedirect('/form/login')
#     else:
#         return HttpResponseRedirect('/form/login')
#
# def login(request):
#     return render( request, 'login.html')




def login (request):
    if request.method=='POST':
        user_form = LoginForm(request.POST)
        # print user_form
        if user_form.is_valid():
            name = user_form.cleaned_data['username']
            psw = user_form.cleaned_data['password']
            user = Formshujus.objects.filter(username=name, password=psw)
            # print user
            if user:
                response = HttpResponseRedirect('/form/index/')
                response.set_cookie('username', name, 5)  # 设置cookie过期时间为5秒
                return response
            else:
                return HttpResponseRedirect('/form/login/')
    else:
        login_form = LoginForm()
        return render(request,template_name='demo.html',context={'user':login_form})



def index(request):
    """
    登录成功后，进入首页。
    """
    username = request.COOKIES.get('username', '')
    return render(request, 'index.html', {'username': username})

def logout(request):
    """
    退出登录系统
    :param request: 
    :return: 
    """
    response = HttpResponse('退出成功')
    response.delete_cookie('username')
    return  response